package com.example.crt_dispatching_center.service;

import com.example.crt_dispatching_center.dto.StaPassengerLingerDTO;
import com.example.crt_dispatching_center.dto.TransferDTO;
import com.example.crt_dispatching_center.entity.Line;
import com.example.crt_dispatching_center.entity.Station;
import com.example.crt_dispatching_center.websocket.DataWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RealTimeDataService {
    @Autowired
    private DataWebSocketHandler dataWebSocketHandler;

    private static final ObjectMapper objectMapper = new ObjectMapper();


    private String convertToJson(Object data) throws Exception {
        return objectMapper.writeValueAsString(data);
    }

    public void processLinePassengerFlow(Line lineData) throws Exception {
        Map<String, Object> data = new HashMap<>();
        data.put("lineName", lineData.getLine());
        data.put("passengerFlow", lineData.getFlow());
        String jsonData = convertToJson(data);
        dataWebSocketHandler.broadcastMessage(jsonData);
    }

    public  void processStaLinger(StaPassengerLingerDTO staPassengerLingerDTO) throws Exception {
        Map<String, Object> data = new HashMap<>();
        data.put("linger", staPassengerLingerDTO.getStationList());
        String jsonData = convertToJson(data);
        System.out.println("Sending JSON data: " + jsonData);
        dataWebSocketHandler.broadcastMessage(jsonData);
    }

    public void processTransfer(TransferDTO transferDTO) throws Exception {
        Map<String, Object> data = new HashMap<>();
        data.put("name", transferDTO.getName());
        data.put("distribute", transferDTO.getDistribute());
        String jsonData = convertToJson(data);
        System.out.println("Sending JSON data: " + jsonData);
        dataWebSocketHandler.broadcastMessage(jsonData);
    }
}
